package com.sskj.xgja.market;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sskj.base.Constant;
import com.sskj.base.adapter.BaseAdapter;
import com.sskj.base.adapter.ViewHolder;
import com.sskj.base.simple.SimpleObserver;
import com.sskj.base.socket.MarketWebSocket;
//import com.sskj.base.socket.WebSocketObserver;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.GlideImageLoader;
import com.sskj.base.utils.GsonUtil;
import com.sskj.base.utils.RxUtils;
import com.sskj.base.utils.WebSocketObserver;
import com.sskj.base.view.DividerLineItemDecoration;
import com.sskj.xgja.MVPFragment;
import com.sskj.xgja.R;
import com.sskj.xgja.WebActivity;
import com.sskj.xgja.ZoomOutPageTransformer;
import com.sskj.xgja.main.MainActivity;
import com.sskj.xgja.market.bean.MarketData;
import com.sskj.xgja.market.bean.SocketMarket;
import com.sskj.xgja.message.data.MessageData;
import com.sskj.xgja.transaction.data.BannerBean;
import com.youth.banner.Banner;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;
import okhttp3.WebSocket;

/**
 * @author Hey
 * Create at  2019/03/20
 */
public class MarketHomeFragment extends MVPFragment<MarketHomePresenter> {
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.banner)
    Banner banner;// Banner图
    @BindView(R.id.edit_coin_name)
    EditText editCoinName;
    @BindView(R.id.market_search)
    ImageView marketSearch;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;// 信息通知栏
    @BindView(R.id.notice_more)
    TextView noticeMore;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private BaseAdapter<MarketData> baseAdapter;
    private MarketWebSocket webSocket;
    private List<MarketData> marketDataList;

    private Disposable disposable;
    private String allCode;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_home;
    }

    @Override
    public MarketHomePresenter getPresenter() {
        return new MarketHomePresenter();
    }

    @Override
    public void initView() {
        initRefreshLayout(smartRefreshLayout);
        smartRefreshLayout.setEnableLoadMore(false);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        tvNotice.setFactory(() -> {
            TextView textView = new TextView(getActivity());
            textView.setTextColor(getResources().getColor(R.color.color_333333));
            return textView;
        });
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.getBanner();
                mPresenter.getMarketList(false);
            }
        });
        ClickUtil.click(marketSearch, view -> {
            if (TextUtils.isEmpty(getText(editCoinName))) {
                ToastUtils.show("请输入股票名称或代码");
                return;
            }
            MarketSearchListActivity.start(getContext(), true, 0, getText(editCoinName));
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.getMarketList(true);
            mPresenter.getBanner();
        }
    }

    @Override
    public void initData() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setPaintWidth(2)
                .setDividerColor(Color.parseColor("#00ffffff"))
        );
        baseAdapter = new BaseAdapter<MarketData>(R.layout.item_market, null, recyclerView, true) {
            @Override
            public void bind(ViewHolder holder, MarketData item) {
//                if (item == null) {
//                    return;
//                }
                holder.setText(R.id.tv_cn_name, item.getName())
                        .setText(R.id.tv_en_name, item.getCode())
                        .setText(R.id.tv_newest_price, item.getPrice())
                        .setText(R.id.tv_up_down, item.getChangeRate());
                if (Float.parseFloat(item.getChange()) >= 0) {
                    holder.setText(R.id.tv_up_down, "+" + item.getChangeRate());
                    holder.setTextColor(R.id.tv_newest_price, color(R.color.red));
                    holder.setBackgroundRes(R.id.tv_up_down, R.drawable.market_red_bg);
                } else {
                    holder.setBackgroundRes(R.id.tv_up_down, R.drawable.market_green_bg);
                    holder.setTextColor(R.id.tv_newest_price, color(R.color.green));
                }
                ClickUtil.click(holder.getView(R.id.market_item), view -> {
                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.currentStock = item;
                    }
                    MarketDetailActivity.start(getContext(), item);
                });
            }
        };
        mPresenter.getMarketList(true);
        mPresenter.getBanner();
        ClickUtil.click(noticeMore, view -> {
            NoticeListActivity.start(getContext());
        });
    }

    private void initSocket() {
        JSONObject message = new JSONObject();
        try {
            message.put("sub", "stock@" + allCode);
            WebSocketObserver webSocketObserver = new WebSocketObserver(Constant.MARKET_WS) {

                @Override
                public void onOpen(WebSocket webSocket, Response response, String type) {
                    webSocket.send(message.toString());
                }
            };
            webSocketObserver
                    .map(s -> new Gson().fromJson(s, SocketMarket.class))
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> webSocketUpdate(data), e -> {

                    });

//            webSocket = MarketWebSocket.getInstance(message.toString());
//            webSocket.observer("market", new WebSocketObserver() {
//                @Override
//                public void onNext(String s) {
//                    SocketMarket data = GsonUtil.GsonToBean(s, SocketMarket.class);
//                    webSocketUpdate(data);
//                }
//            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public void finishRefresh() {
        smartRefreshLayout.finishLoadMore();
        smartRefreshLayout.finishRefresh();
    }

    private void webSocketUpdate(SocketMarket data) {
//        RxBus.getDefault().post(data);
        if (marketDataList != null && data != null) {
            for (int i = 0; i < marketDataList.size(); i++) {
                if (data == null || marketDataList.get(i) == null) {
                    return;
                }
                if (data.getCode().equals(marketDataList.get(i).getCode())) {
                    MarketData data1 = new MarketData();
                    data1.setCode(data.getCode());
                    data1.setName(data.getName());
                    data1.setPrice(data.getPrice() + "");
                    data1.setChangeRate(data.getChangeRate());
                    data1.setChange(data.getChange() + "");
                    data1.setHigh(data.getHigh() + "");
                    data1.setLow(data.getLow() + "");
                    marketDataList.set(i, data1);
                    baseAdapter.notifyDataSetChanged();
                }
            }

        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webSocket != null) {
            webSocket.disposeByTag("market");
        }
        if (disposable != null) {
            disposable.dispose();
        }
    }

    public static MarketHomeFragment newInstance() {
        MarketHomeFragment fragment = new MarketHomeFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    public void setMarketList(List<MarketData> data) {
        marketDataList = data;

        baseAdapter.setNewData(marketDataList);
        if (data==null)
            return;
        StringBuilder stringBuilder = new StringBuilder();
        Flowable.fromIterable(data)
                .map(marketData -> "|" + marketData.getCode())

                .subscribe(s -> {
                    stringBuilder.append(s);
                });
        allCode = stringBuilder.substring(1);
        initSocket();
    }

    public void setBanner(List<BannerBean> data) {
        if (data != null) {
            List<String> urls = new ArrayList<>();
            for (BannerBean bean : data) {
                urls.add(bean.getBanner_url());
            }
            if (urls.size() == 1) {
                urls.add(data.get(0).getBanner_url());
            }
            banner.setImages(urls);
            banner.setOffscreenPageLimit(3);
            banner.setPageTransformer(false, new ZoomOutPageTransformer());
            banner.start();
        }
    }

    public void setNotice(List<MessageData.Message> data) {
        if (data != null && data.size() != 0) {
            if (disposable != null) {
                disposable.dispose();
            }
            Observable.interval(0, 5, TimeUnit.SECONDS)
                    .compose(RxUtils.transform())
                    .subscribe(new SimpleObserver<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            disposable = d;
                        }

                        @Override
                        public void onNext(Long i) {
                            if (tvNotice != null) {
                                MessageData.Message message = data.get((int) (i % data.size()));
                                String title = message.getTitle();
                                tvNotice.setText(title);
                                ClickUtil.click(tvNotice, view -> {
                                    WebActivity.start(getContext(), message.getId() + "", 1);
                                });
                            }
                        }
                    });
        }

    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    @Override
    public boolean immersionBarEnabled() {
        return true;
    }
}
